package validators

import (
	"fmt"
	"math"
	"regexp"
	"strconv"
	"strings"
	"time"

	"order-validation-api/models"
)

// GlobalValidator 全局验证器
type GlobalValidator struct {
	orderIDGenerator models.OrderIDGenerator
}

// NewGlobalValidator 创建新的全局验证器
func NewGlobalValidator(generator models.OrderIDGenerator) *GlobalValidator {
	return &GlobalValidator{
		orderIDGenerator: generator,
	}
}

// ValidateOrder 验证订单的全局规则
func (gv *GlobalValidator) ValidateOrder(order *models.Order) *models.ValidationResult {
	result := &models.ValidationResult{IsValid: true}

	// 验证OrderID格式
	if !gv.validateOrderIDFormat(order.OrderID) {
		result.AddError("OrderID format is invalid. Expected format: QF-{TodaysDate}-{index}")
	}

	// 验证货币代码
	if !gv.validateCurrency(order.Currency) {
		result.AddError(fmt.Sprintf("Currency '%s' is not a valid ISO 4217 currency code", order.Currency))
	}

	// 验证订单类型
	if !gv.validateOrderType(order.Type) {
		result.AddError(fmt.Sprintf("Order type '%s' is invalid. Must be 'Limit' or 'Market'", order.Type))
	}

	// 验证篮子订单规则
	if order.IsBasketOrder() {
		gv.validateBasketOrder(order, result)
	} else {
		// 非篮子订单不应该有子订单
		if len(order.ChildOrders) > 0 {
			result.AddError("Non-basket order should not have child orders")
		}
	}

	// 验证基本字段
	gv.validateBasicFields(order, result)

	return result
}

// validateOrderIDFormat 验证OrderID格式
func (gv *GlobalValidator) validateOrderIDFormat(orderID string) bool {
	// QF-{TodaysDate}-{index} 格式验证
	pattern := `^QF-(\d{8})-(\d+)$`
	re := regexp.MustCompile(pattern)
	matches := re.FindStringSubmatch(orderID)
	
	if len(matches) != 3 {
		return false
	}

	// 验证日期格式
	dateStr := matches[1]
	_, err := time.Parse("20060102", dateStr)
	if err != nil {
		return false
	}

	// 验证索引是正整数
	index, err := strconv.Atoi(matches[2])
	return err == nil && index > 0
}

// validateCurrency 验证货币代码
func (gv *GlobalValidator) validateCurrency(currency string) bool {
	return models.IsValidISO4217Currency(currency)
}

// validateOrderType 验证订单类型
func (gv *GlobalValidator) validateOrderType(orderType models.OrderType) bool {
	return orderType == models.OrderTypeLimit || orderType == models.OrderTypeMarket
}

// validateBasketOrder 验证篮子订单规则
func (gv *GlobalValidator) validateBasketOrder(order *models.Order, result *models.ValidationResult) {
	// 篮子订单必须有子订单
	if len(order.ChildOrders) == 0 {
		result.AddError("Basket order must have child orders")
		return
	}

	// 验证子订单权重总和等于1
	totalWeight := order.GetTotalChildWeight()
	if math.Abs(totalWeight-1.0) > 0.0001 { // 使用小的容差值处理浮点数精度问题
		result.AddError(fmt.Sprintf("Sum of child order weights must equal 1.0, got %.4f", totalWeight))
	}

	// 递归验证每个子订单
	for i, child := range order.ChildOrders {
		childResult := gv.ValidateOrder(&child)
		if !childResult.IsValid {
			for _, err := range childResult.Errors {
				result.AddError(fmt.Sprintf("Child order %d: %s", i+1, err))
			}
		}

		// 子订单不应该再有子订单（避免嵌套过深）
		if child.IsBasketOrder() {
			result.AddError(fmt.Sprintf("Child order %d should not have nested child orders", i+1))
		}
	}
}

// validateBasicFields 验证基本字段
func (gv *GlobalValidator) validateBasicFields(order *models.Order, result *models.ValidationResult) {
	// 验证必填字段
	if strings.TrimSpace(order.OrderID) == "" {
		result.AddError("OrderID is required")
	}

	if strings.TrimSpace(order.Symbol) == "" {
		result.AddError("Symbol is required")
	}

	if strings.TrimSpace(order.Destination) == "" {
		result.AddError("Destination is required")
	}

	if strings.TrimSpace(order.ClientID) == "" {
		result.AddError("ClientID is required")
	}

	// 验证数值字段
	if order.NotionalAmount <= 0 {
		result.AddError("NotionalAmount must be greater than 0")
	}

	if order.Weight < 0 || order.Weight > 1 {
		result.AddError("Weight must be between 0 and 1")
	}
}